<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link	   http://jvitals.com
 * @since	  File available since initial release
 */

class ASubscriptionHelper {

	function newPost($post_id, $forum_id, $only_mods = false) {

		$config =& JFactory::getConfig();
		$parser = & $this->helper('parser');
		$eprocess = & $this->helper('emailprocessor');
		$parser->enable_img = 'True';

		$post_model = &Model::getInstance('PostModel');
		$post = $post_model->load($post_id);
		$topic_id = $post['topic_id'];

		$s_model = &Model::getInstance('SubscriptionModel');
		if (!$only_mods) {
			$subscribers = $s_model->loadSubscribers($topic_id, $forum_id);
		} else {
			$subscribers = $s_model->loadSubscribersModsAdmins($topic_id, $forum_id);
		}
		
		$topic_model = &Model::getInstance('TopicModel');
		$topic = $topic_model->load($topic_id);

		/*
		$username - name of user posted message
		$subject - topic subject
		$message - posted message
		$url - post url
		$unsubscribe - unsubscribe url
		*/
		
		$num_posts = $topic['num_replies'] + 1;
		
		// Agora::redirect(Agora::makeURL($url). "#p$post_id");

		// Agora::showMessage('User Name='.$post['poster']);
		// $this->view->assign('username',$post['poster']);
		// $this->view->assign('subject',$topic['subject']);
		// $this->view->assign('message',$post['message']);

		// $u_url = Agora::makeURL(array('task'=>'topic','action'=>'unsubscribe','id'=>$topic_id));
		// $this->view->assign('unsubscribe',$u_url);
		
		$poster = $post['poster'];
		if ($this->agora_config['o_fullnames_enabled'] && $post['poster_id']) {
			$user_model = & Model::getInstance('UserModel');
			$result = $user_model->load($post['poster_id']);
			if (@$result['name']) {
				$poster = $result['name'];
			}
		}
		
		if (!$only_mods) {
			$dispatcher =& JDispatcher::getInstance();
			$dispatcher->trigger('onAfterAgoraPost', array($post_id, $forum_id, $post, $topic, $poster, $this->agora_config, $parser, $eprocess));
			$messagebody = trim($this->agora_config['o_subscr_messg']);
			$messagesubject = trim($this->agora_config['o_subscr_subject']);
			$num_replies = 0;
		} else {
			$messagebody = trim($this->agora_config['o_moderated_messg']);
			$messagesubject = trim($this->agora_config['o_moderated_subject']);
			$db = &JFactory::getDBO();
			$db->setQuery('SELECT count(*) as count FROM #__agora_posts WHERE topic_id = ' . (int)$topic_id);
			$num_replies = (int)$db->loadResult();
		}
		
		// We use #### for triming old message from reply
		// TODO: this doesn't seem to be working? #28
		//$messagebody = '####<br /> <br />' . $messagebody . '<br /> <br />####<br />';
		
		$foundMails = array();
		
		foreach ($subscribers as $i => $user) {
			// skip users if they've been sent mails :P
			if (in_array($user['email'], $foundMails)) continue;
			$foundMails[] = $user['email'];
			
			if (0 == $post['poster_id'] || $post['poster_id'] != $user['id']){

				$per_page = intval($user['disp_posts']) > 0 ? $user['disp_posts'] :  $this->agora_config['o_disp_posts_default'];
				$num_pages = ceil($num_posts / $per_page);
				$page = $num_pages;
				$url = array('task'	=>'topic', 'id'	=>$topic_id);

				if ($num_pages > 1) {
					$url['p'] = $num_pages;
				}

				$message = $post['message'];
				$message = $parser->smilies($message);
				$message = $parser->links($message);
				$message = $parser->bbcode($message,0,true);
				$message = nl2br($message);
				
				if ($this->agora_config['o_fullnames_enabled']) {
					$body = $this->processBody($eprocess, $messagebody, $user['id'], $user['name'], $user['email'], $poster, $config->getValue( 'config.sitename' ), JURI::root(), $topic['subject'], $message, $forum_id, $topic_id, $post_id, $page, $num_posts);
					$emailSubject = $this->processBody($eprocess, $messagesubject, $user['id'], $user['name'], $user['email'], $poster, $config->getValue( 'config.sitename' ), JURI::root(), $topic['subject'], $message, $forum_id, $topic_id, $post_id, $page, $num_posts);
				} else {
					$body = $this->processBody($eprocess, $messagebody, $user['id'], $user['username'], $user['email'], $poster, $config->getValue( 'config.sitename' ), JURI::root(), $topic['subject'], $message, $forum_id, $topic_id, $post_id, $page, $num_posts);
					$emailSubject = $this->processBody($eprocess, $messagesubject, $user['id'], $user['username'], $user['email'], $poster, $config->getValue( 'config.sitename' ), JURI::root(), $topic['subject'], $message, $forum_id, $topic_id, $post_id, $page, $num_posts);
				}
				$emailSubject .= ((int)$topic_id ? ' [topic:' . (int)$topic_id . ']' : '');

				// $this->view->fetchTemplate('email'.DS.'en-GB'.DS.'topic_subscription.tpl');
				
				$mail = JFactory::getMailer();
				
				$o_email_sender = trim($this->agora_config['o_email_sender']);
				if ($o_email_sender) {
					$sender_arr = explode(',', $o_email_sender);
					if (count($sender_arr) == 2) {
						$mail->setSender(array($sender_arr[0], $sender_arr[1]));
					} else {
						$mail->setSender($o_email_sender);
					}
				}
				
				if (!$this->agora_config['o_subscrb_emails_type'] || !$user['emailed']) {
					$mail->addRecipient( $user['email']);
					$mail->setSubject($emailSubject);
					$mail->setBody( $body );

					$mail->AltBody = $eprocess->getPlainData();
					$mail->IsHTML(true);
					$mail->Send();
					if (!$mail->IsError() && $this->agora_config['o_subscrb_emails_type']) {
						$s_model->updateSubscriberEmailed($user['id'], $user['topic_id'], $user['forum_id'], '1');
					}
				}
			}
			// on every 50 mails sent, give more time to the script
			if ($i > 0 && !($i%50)) {
				set_time_limit(30);
			}
		}
	}
	
	function processBody($eprocess, $body, $userid, $username, $useremail, $poster,  $sitename, $siteurl, $title, $message, $forum, $topic, $post, $postpage, $num_replies) {
		$eprocess = & $this->helper('emailprocessor');
		$eprocess->setData($body);
		$eprocess->setUserId($userid);
		$eprocess->setUserName($username);
		$eprocess->setEmail($useremail);
		$eprocess->setSiteName($sitename);
		$eprocess->setSiteURL($siteurl);
		$eprocess->setItemId(JRequest::getVar('Itemid'));
		$eprocess->setTitle($title);
		$eprocess->setMessage($message);
		$eprocess->setForumId($forum);
		$eprocess->setTopicId($topic);
		$eprocess->setPostId($post);
		$eprocess->setPoster($poster);
		$eprocess->setPostPage($postpage);
		$eprocess->setNumReplies($num_replies);
		return $eprocess->Process();
	}
	
	function & helper($name) {
		static $loaded;
		if (!isset($loaded[$name])) {
			ainclude('helpers|'.$name);
			$classname = 'A'.ucfirst($name).'Helper';
			$helper = new $classname;
			$loaded[$name] = & $helper;

			$helper->agora_config = $this->agora_config;
			$helper->agora_user = $this->agora_user;
			$helper->controller = $this;
			if (method_exists($helper,'assign'))
			$helper->assign($this->view);
		}

		return $loaded[$name];
	}
	
	function assign(& $view) {
		$this->view = & $view;
	}
	
}


